<?php

namespace tool;

use OSS\Core\OssException;
use OSS\OssClient;

class Res
{

    public static function upload($dir, $file = "file", $type = "")
    {
        $del = false;
        if (strpos($file, "http") !== false) {
            $del = true;
            $temp = Res::gettmpfile();
            ob_start();
            readfile($file);
            $img = ob_get_contents();
            ob_end_clean();
            file_put_contents($temp, $img);
            $filename = $temp;

        } elseif (strpos($file, "tmp") !== false) {

            $del = true;
            $filename = $file;

        } else {
            $file_obj = request()->file($file);
            if (empty($file_obj)) return null;
            $info = $file_obj->getInfo();
            $name = $info['name'];
            $type = substr(strrchr($name, '.'), 1);
            $filename = $info['tmp_name'];
        }
        $r = uniqid();


        $oss_config = config("oss");
        $aliyun_config = config("aliyun");
        $object = "{$oss_config['dir']}/$dir/$r.$type";
        $ossClient = new OssClient($aliyun_config['accessKeyId'], $aliyun_config['accessKeySecret'], $oss_config['endpoint']);
        $filePath = $filename;
        try {
            $bucket = $oss_config['bucket'];
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch (OssException $e) {
            return null;
        }

        if ($del) {
            unlink($filename);
        }
        return $object;

    }

    public static function gettmpfile()
    {
        return tempnam("/tmp", "t");
    }

    public static function getvideo($video)
    {
        $aliyun_config = config("aliyun");
        $oss_config = config("oss");
        $time=date("YmdHi");
        $key=$oss_config['vcdnkey'];
        $domain=$oss_config['vurl'];
        $filename="/".$video;

        $sstring = $key.$time.$filename;

        $md5=md5($sstring);

        $url=$domain.$time."/".$md5.$filename;
        return $url;
    }
}